package com.bjbn.service;

import com.bjbn.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;

/**
 * WebAPI服务类
 *
 * @author bjbn
 */
@Service
public class Webapi4PvmcsService {

    @Autowired
    @Qualifier("httpWebClient")
    private WebClient httpWebClient;

    @Value("${external.api.headers.appkey}")
    private String appkey;

    @Value("${external.api.headers.appsecret}")
    private String appsecret;

    /**
     * 转发API请求（HTTP）
     *
     * @param endpoint    API端点
     * @param version     api版本号
     * @param requestBody 请求体
     * @return 响应结果
     */
    private Mono<Map<String, Object>> forwardHttpApiRequest(String endpoint, String version, Object requestBody) {
        // 请求id {请求方系统缩略语}-{时间字符串}-{UUID前8位}
        String systemName = "DTS";
        String requestId = systemName + "-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "-" + UUID.randomUUID().toString().substring(0, 8);

        String xHwId = "jichang_io.runway.anti.intrusion_Tr_PVMCS";
        String xHwAppkey = "5wn00Zfz$/Ek!$n4Gk.2A@fmlD=p7wd1Db5.dY+jg8gY.iC=$j8YZ/W8@82/5H3C";
        return httpWebClient.post()
                .uri(endpoint)
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("Content-Type", "application/json")
                .header("appkey", appkey)
                .header("appsecret", appsecret)
                .header("timestamp", String.valueOf(System.currentTimeMillis()))
                .header("version", version)
                .header("requestId", requestId)
                .bodyValue(requestBody)
                .retrieve()
                // 关键修复：保留后端原始错误响应
                .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(),
                        response -> response.bodyToMono(String.class)
                                .flatMap(errorBody -> {
                                    String errorMsg = String.format(
                                            "API调用失败: [状态码=%s] [requestId=%s] [URL=%s] [响应体=%s]",
                                            response.statusCode(), requestId, endpoint, errorBody
                                    );
                                    System.err.println(errorMsg);
                                    // 抛出异常，让上游处理或返回500
                                    return Mono.error(new RuntimeException(errorMsg));
                                })
                )
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                // 只处理网络异常等底层错误，不处理HTTP业务错误
                .onErrorResume(WebClientRequestException.class, e -> {
                    String errorMsg = String.format(
                            "网络异常: [requestId=%s] [URL=%s] [错误=%s]",
                            requestId, endpoint, e.getMessage()
                    );
                    System.err.println(errorMsg);
                    return Mono.error(new RuntimeException(errorMsg));
                });
    }


    // ==================== 大场景拼接及跑道防入侵系统API ====================
    public Mono<Map<String, Object>> pvmcsEventList(PvmcsEventRequest request) {
        return forwardHttpApiRequest("/CAN/Tr_PVMCS/runwayAntiIntrusion/V1api/v1/getEventList", "1.0", request);
    }
} 